import 'dart:io';
import 'dart:typed_data';
import 'package:Smart/utils/string_util.dart';
import 'package:path_provider/path_provider.dart';

/// #### APP缓存目录管理
///
/// 缓存目录结构
///
/// - cache
///   - images
///   - videos
///   - ...
class GSFileCacheUtil {
  /// 统一缓存目录
  static Future<String> getCache() async {
    String rootDir = "";
    if (Platform.isIOS) {
      rootDir = (await getApplicationDocumentsDirectory()).path;
    } else {
      rootDir = (await getExternalStorageDirectory()).path;
    }
    await checkDirectoryExists("$rootDir/cache");
    return rootDir;
  }

  /// 视频缓存目录
  static Future<String> getVideosCache() async {
    String rootDir = await getCache();
    String videosCache = "$rootDir/videos";
    await checkDirectoryExists(videosCache);
    return videosCache;
  }

  // URI的本地文件路径
  static Future<String> localPathWithUrl(String url) async {
    var uri = Uri.parse(url);
    String videoCache = await GSFileCacheUtil.getVideosCache();
    String filePath = videoCache +
        "/" +
        StringUtil.md5Str(url) +
        "." +
        uri.pathSegments.last.split(".").last;
    return filePath;
  }

  /// 图片缓存目录
  static Future<String> getImagesCache() async {
    String rootDir = await getCache();
    String imagesCache = "$rootDir/images";
    await checkDirectoryExists(imagesCache);
    return imagesCache;
  }

  /// 检测并创建目录
  static Future<bool> checkDirectoryExists(String path) async {
    var dir = Directory(path);
    try {
      bool exists = await dir.exists();
      if (!exists) {
        var newDir = await dir.create(recursive: true);
        print("创建缓存目录：$path");
        return await newDir.exists();
      } else {
        return true;
      }
    } catch (e) {
      print("目录创建失败：$path\n错误信息：$e");
      return false;
    }
  }

  /// 检查文件是否存在
  static Future<bool> checkFileExists(String filePath) async {
    var file = File(filePath);
    return await file.exists();
  }

  /// 查询文件夹中文件
  Future<List<FileSystemEntity>> queryFiles({String path}) async {
    if (path == null) return [];
    Directory directory = new Directory(path);
    return directory.listSync();
  }

  // 删除单个文件
  static Future<bool> deleteFile(String path) async {
    if (path == null) return false;
    try {
      var file = File(path);
      if (await file.exists()) {
        await File(path).delete();
      }
      return true;
    } catch (e) {
      return false;
    }
  }

  // 删除目录
  static Future deleteDirectory(String path, {bool recursive = false}) async {
    if (path == null) return false;
    try {
      var dir = Directory(path);
      if (await dir.exists()) {
        await dir.delete(recursive: recursive);
      }
      return true;
    } catch (e) {
      return false;
    }
  }

  // 保存文件
  static Future<File> saveFile(String savePath, Uint8List bytes) async {
    return await File(savePath).writeAsBytes(bytes);
  }
}
